<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>HTML DOM - Get size of the selected file</title>
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="stylesheet" href="/css/demo.css" />
        <link rel="preconnect" href="https://fonts.gstatic.com" />
        <link
            rel="stylesheet"
            href="https://fonts.googleapis.com/css2?family=Inter&family=Source+Code+Pro&display=swap"
        />
    </head>
    <body>
        <div style="align-items: center; display: flex; justify-content: center; padding: 6rem 0">
            <div
                style="
                    align-items: center;
                    border: 1px solid #cbd5e0;
                    display: flex;
                    justify-content: center;
                    padding: 0.5rem;
                "
            >
                <input type="file" id="upload" />
                <div id="size"></div>
            </div>
        </div>

        <script>
            document.addEventListener('DOMContentLoaded', function () {
                // Query the elements
                const fileEle = document.getElementById('upload');
                const sizeEle = document.getElementById('size');

                // Convert the file size to a readable format
                const formatFileSize = function (bytes) {
                    const sufixes = ['B', 'kB', 'MB', 'GB', 'TB'];
                    const i = Math.floor(Math.log(bytes) / Math.log(1024));
                    return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${sufixes[i]}`;
                };

                fileEle.addEventListener('change', function (e) {
                    const files = e.target.files;
                    if (files.length === 0) {
                        // Hide the size element if user doesn't choose any file
                        sizeEle.innerHTML = '';
                        sizeEle.style.display = 'none';
                    } else {
                        // File size in bytes
                        const size = files[0].size;

                        // Convert it to a readable format
                        sizeEle.innerHTML = formatFileSize(size);

                        // Display it
                        sizeEle.style.display = 'block';
                    }
                });
            });
        </script>
    </body>
</html>
